/**
 * Created by Administrator on 2016/11/16.
 */

var express = require('express');
var router = express.Router();
var co = require('co');
var seqModule = require('./createModules');
var seq = new seqModule();

var formidable = require('formidable');
var getIP = require('./getIP');
require('./uuid');
var fs = require('fs');

//添加
router.post('/addPowerRole', function(req, res, next) {
    co(function () {
        if (req.method.toLowerCase() == 'post') {
            var form = new formidable.IncomingForm();
            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                var ids = fields.idStr;
                var idArr = ids.split(",");
                var menuRoleSql = "insert into  power_role_menu values ";
                for(var i=0;i<idArr.length;i++){
                    menuRoleSql+=" ('"+Math.uuid()+"','"+idArr[i]+"','"+fields.id+"'),";
                }
                menuRoleSql = menuRoleSql.substring(0,menuRoleSql.lastIndexOf(","));
                delete fields.idStr;
                seq.powerRoleModule.create(fields).then(function (results) {
                    seq.sequelize.query(menuRoleSql).spread(function(rows){
                        res.redirect(getIP+'power/powerRoleList.html');
                    })

                });
            });
        }
    }).catch(function(e) {
        res.json({'success':false,'msg':'添加失败'});
        console.log(e);
    })
});

//删除
router.get('/deletePowerRole', function(req, res, next) {
    co(function () {
         var params=req.query.params;
         var arr=params.split(",");
         var paramT=[arr];
        seq.powerRoleModule.destroy({'where':{'id':paramT}}).then(function(results){
            res.json({"success":true,"msg":"删除成功","rows":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'删除失败'});
        console.log(e);
    })
});

//查询
router.get('/getPowerRolePage', function(req, res, next) {
    co(function () {
        var page = parseInt(req.query.page);
        var params={};
        var paramT={};
        var paramU={};

        if(req.query.id != undefined){
            params["id"]=req.query.id;
        }
        if(req.query.parentId != undefined){
            params["parentId"]=req.query.parentId;
        }
        //模糊查询
        if(req.query.roleName != undefined){
            paramU["$like"]="%"+req.query.roleName+"%";
            params["roleName"]=paramU;
        }
        paramT["where"]=params;
        paramT["order"]=[["updateTime",'DESC']];
        if(req.query.page != undefined && req.query.rows !=undefined){
            paramT["offset"]=parseInt(req.query.page);
            paramT["limit"]=parseInt(req.query.rows);
        }
        seq.powerRoleModule.findAndCountAll(paramT).then(function(result){
            res.json({"success":true,"msg":"查询成功","page":page,"total":result.count,"result":result.rows});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'查询失败'});
        console.log(e);
    })
});




router.get('/getPowerRoles', function(req, res, next) {
    co(function () {
        var params={};
        var paramT={};
        var paramU={};

        if(req.query.id != undefined){
            params["id"]=req.query.id;
        }
        if(req.query.parentId != undefined){
            params["parentId"]=req.query.parentId;
        }
        //模糊查询
        if(req.query.roleName != undefined){
            paramU["$like"]="%"+req.query.roleName+"%";
            params["roleName"]=paramU;
        }
        paramT["where"]=params;
        paramT["order"]=[["updateTime",'DESC']];
        seq.powerRoleModule.findAll(paramT).then(function(result){
            res.json({"success":true,"msg":"查询成功","result":result});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'查询失败'});
        console.log(e);
    })
});

//修改
router.post('/updatePowerRole', function(req, res, next) {
    co(function () {
        if (req.method.toLowerCase() == 'post') {
            var form = new formidable.IncomingForm();
            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                var params = {};
                var paramT = {};
                var paramU = {};
                paramU.id = fields.id;
                if(fields.parentId != undefined){
                    params.parentId = fields.parentId;
                }
                if(fields.roleName != undefined){
                    params.roleName = fields.roleName;
                }
                if(fields.updateTime != undefined){
                    params.updateTime = fields.updateTime;
                }
                if(fields.updateUserName != undefined){
                    params.updateUserName = fields.updateUserName;
                }
                paramT.where = paramU;

                var ids = fields.idStr;
                var idArr = ids.split(",");
                var paramL = {};
                var paramM = {};
                paramL.roleId = fields.id;
                paramM.where = paramL;

                var menuRoleSql = "insert into  power_role_menu values ";
                for(var i=0;i<idArr.length;i++){
                    menuRoleSql+=" ('"+Math.uuid()+"','"+idArr[i]+"','"+fields.id+"'),";
                }
                menuRoleSql = menuRoleSql.substring(0,menuRoleSql.lastIndexOf(","));
                delete fields.idStr;
                seq.powerRoleModule.update(params,paramT).then(function (results) {
                    seq.powerRoleMenuModule.destroy(paramM).then(function(result){
                        seq.sequelize.query(menuRoleSql).spread(function(rows){
                            res.redirect(getIP+'power/powerRoleList.html');
                        })
                    });
                });
            });
        }
    }).catch(function(e) {
        res.json({'success':false,'msg':'修改失败'});
        console.log(e);
    })
});

module.exports = router;
